/*
 * @lc app=leetcode id=71 lang=cpp
 *
 * [71] Simplify Path
 */
class Solution {
public:
    string simplifyPath(string path) {
        deque<string> dq;
        string p = "";
        int len = path.length();
        if (len < 1 || path[0] != '/') {
            return p;
        }

        int i=1;
        while(i < len) {
            int idx = i;
            while(idx < len && path[idx] != '/') {
                idx++;
            }

            if (idx > i) {
                if (idx == i+1) {
                    if (path[i] != '.') {
                        dq.push_back(path.substr(i, idx-i));
                    }
                } else if (idx == i+2) {
                    if (path[i] == '.' && path[i+1] == '.') {
                        if (dq.size() > 0) {
                            dq.pop_back();
                        }
                    } else {
                        dq.push_back(path.substr(i, idx-i));
                    }
                } else {
                    dq.push_back(path.substr(i,idx-i));
                }
            }
            i = idx+1;
        }

        p = "/";
        for (int i=0; i<dq.size(); i++) {
            if (i > 0) {
                p += '/';
            }
            p += dq[i];
        }
        return p;
    }
};

